package com.insyte.fragments;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.insyte.R;
import com.insyte.adapters.ExpandableInterestAdapter;
import com.insyte.adapters.InterestFBAdapter;
import com.insyte.adapters.MyInterestAdapter;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.config.InsyteEnums;
import com.insyte.model.Category;
import com.insyte.model.CategoryOfInterest;
import com.insyte.model.FacebookData;
import com.insyte.model.InteresetObject;
import com.insyte.model.Paging;
import com.insyte.model.User;
import com.insyte.networks.ParserUtils;
import com.insyte.utils.Initialize;
import com.insyte.utils.NonSwipeableViewPager;
import com.insyte.utils.ParserFaceBookUntils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProfileFavourisFragment extends Fragment implements View.OnClickListener {
    //
    private CheckBox chk_pull_facebook;
    private Spinner spn_dating_status;
    private ImageView img_dating_status, imgBack;
    private Button btn_next;
    private TextView tv_pull_from_facebook;
    private String arrDattingStatus[] = {"Married", "Single", "Divorced"};
    //List<CategoryOfInterest> itemList = new ArrayList<CategoryOfInterest>();
    private ExpandableListView exp_interest;
    private ListView exp_my_interest;
    private LinearLayout ln_pull_facebook;
    private ArrayAdapter<String> adapter;
    private ExpandableInterestAdapter exp_adapter;
    private MyInterestAdapter my_interest_adapter;
    private InterestFBAdapter fb_interest_adapter;
    private String url_get_interests = Constants.URL_API + "/interests?token=%s";
    private String url_pull_interests_fb = "https://graph.facebook.com/v2.3/me/likes?access_token=%s";
    private Initialize initialize;
    private ProgressDialog progressDialog;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private Map<String, Object> params;
    AQuery aQuery;
    private List<CategoryOfInterest> lstCategoryOfInterests = new ArrayList<>();
    private List<CategoryOfInterest> lstCategoriesInterests = new ArrayList<>();
    private List<InteresetObject> lstInterests = new ArrayList<>();
    private List<Category> lstFBInterests = new ArrayList<>();
    NonSwipeableViewPager viewPager;
    private User user;

    public interface OnChildItemListener {
        public void onClick(InteresetObject object);
    }

    public interface OnMyInterestItemListener {
        public void onClick(InteresetObject object);
    }

    public interface OnFBInterestItemListener {
        public void onClick(Category object);
    }

    public ProfileFavourisFragment setViewPager(NonSwipeableViewPager viewPager) {
        this.viewPager = viewPager;
        return this;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        aQuery = new AQuery(getActivity());
        user = InsyteApp.getInstance().getUser();
        prefs = getActivity().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
        editor = prefs.edit();
        params = new HashMap<String, Object>();
        initialize = new Initialize(getActivity());
        progressDialog = initialize.createProgressDialog("Loading");
        initExpandableData();
    }

    private void initExpandableData() {
        lstCategoryOfInterests.clear();
        if (lstCategoriesInterests.size() > 0) lstCategoriesInterests.clear();
        String url_getInterest = String.format(url_get_interests, InsyteApp.getInstance().getUser().getToken());
        aQuery.ajax(url_getInterest, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject js, AjaxStatus status) {
                progressDialog.dismiss();
                if (result != null) {
                    try {
                        if (js.has("code")) {
                            if (js.getInt("code") == 1) {
                                lstCategoryOfInterests = ParserUtils.parerInterest(js);
                                Log.d("interestSize", lstCategoryOfInterests.size() + "");
                                lstCategoriesInterests.addAll(lstCategoryOfInterests);
                                exp_adapter.notifyDataSetChanged();
                            }
                            //initialize.showToast(js.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    initialize.showToast("check server");
                }
            }
        }.header("Content-Type", "application/x-www-form-urlencoded"));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragmentS
        View view = inflater.inflate(R.layout.fragment_profile_favouris, container, false);
        getViewController(view);
        if (InsyteApp.getTypeLoginEnum(getActivity()).equals(InsyteEnums.TypeLogin.FB)) {
            ln_pull_facebook.setEnabled(true);
            chk_pull_facebook.setEnabled(true);
            tv_pull_from_facebook.setEnabled(true);
        } else {
            ln_pull_facebook.setEnabled(false);
            chk_pull_facebook.setEnabled(false);
            tv_pull_from_facebook.setEnabled(false);
        }
        if (user.getDating_status() != null) {
            if (user.getDating_status().equalsIgnoreCase("single")) {
                spn_dating_status.setSelection(1);
            } else {
                spn_dating_status.setSelection(0);
            }
        }
        return view;
    }

    private void getViewController(View v) {
        btn_next = (Button) v.findViewById(R.id.btn_next);
        ln_pull_facebook = (LinearLayout) v.findViewById(R.id.ln_pull_facebook);
        btn_next.setOnClickListener(this);
        chk_pull_facebook = (CheckBox) v.findViewById(R.id.chk_pull_facebook);
        chk_pull_facebook.setBackgroundResource(R.drawable.ic_un_check);
        chk_pull_facebook.setEnabled(false);
        spn_dating_status = (Spinner) v.findViewById(R.id.spn_dating_status);
        tv_pull_from_facebook = (TextView) v.findViewById(R.id.tv_pull_from_facebook);
        tv_pull_from_facebook.setEnabled(false);
        imgBack = (ImageView) v.findViewById(R.id.imgBack);
        img_dating_status = (ImageView) v.findViewById(R.id.img_dating_status);
        btn_next = (Button) v.findViewById(R.id.btn_next);
        exp_interest = (ExpandableListView) v.findViewById(R.id.exp_interest);
        exp_my_interest = (ListView) v.findViewById(R.id.exp_my_interest);
        exp_adapter = new ExpandableInterestAdapter(getActivity(), lstCategoriesInterests, new OnChildItemListener() {
            @Override
            public void onClick(InteresetObject object) {
                //lstCategoriesInterests.remove(object);
                if(checkInterestExits(object.getName()))
                    return;
                lstInterests.add(0, object);
                my_interest_adapter.notifyDataSetChanged();
                exp_adapter.notifyDataSetChanged();
                fb_interest_adapter.notifyDataSetChanged();
            }
        });
        my_interest_adapter = new MyInterestAdapter(getActivity(), lstInterests, new OnMyInterestItemListener() {
            @Override
            public void onClick(InteresetObject object) {
                lstInterests.remove(object);
                my_interest_adapter.notifyDataSetChanged();
            }
        });
        fb_interest_adapter = new InterestFBAdapter(getActivity(), lstFBInterests, new OnFBInterestItemListener() {
            @Override
            public void onClick(Category object) {
                lstInterests.remove(object);
                my_interest_adapter.notifyDataSetChanged();
            }
        });
        exp_interest.setAdapter(exp_adapter);
        if (InsyteApp.getTypeLoginEnum(getActivity()).equals(InsyteEnums.TypeLogin.FB)) {
            exp_my_interest.setAdapter(fb_interest_adapter);
        } else {
            exp_my_interest.setAdapter(my_interest_adapter);
        }
        //exp_my_interest.setAdapter(my_interest_adapter);
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, arrDattingStatus);
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
        spn_dating_status.setAdapter(adapter);
        ln_pull_facebook.setOnClickListener(this);
        imgBack.setOnClickListener(this);
        chk_pull_facebook.setOnClickListener(this);
        tv_pull_from_facebook.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pull_from_facebook:
            case R.id.ln_pull_facebook:
            case R.id.chk_pull_facebook:
                if (!chk_pull_facebook.isChecked()) {
                    chk_pull_facebook.setBackgroundResource(R.drawable.ic_check);
                    //String url_pull_interests = String.format(url_pull_interests_fb, InsyteApp.getFacebookToken(prefs));
                    //Log.e("", url_pull_interests);
                    if (lstInterests.size() > 0) lstInterests.clear();
                    if (lstFBInterests.size() > 0) lstFBInterests.clear();
                    lstFBInterests.addAll(InsyteApp.getInstance().getUser().getLsInterestFB());
                    fb_interest_adapter.notifyDataSetChanged();
                } else {
                    chk_pull_facebook.setBackgroundResource(R.drawable.ic_un_check);
                }
                break;
            case R.id.imgBack:
                viewPager.setCurrentItem(0);
                break;
            case R.id.btn_next:
                Log.e("dating", spn_dating_status.getSelectedItem().toString());
                String interest = "";
                if (lstInterests.size() > 0) {
                    for (int i = 0; i < lstInterests.size(); i++) {
                        if (i == lstInterests.size() - 1)
                            interest = interest + "," + lstInterests.get(i).getName();
                        else if (i == 0) {
                            interest = lstInterests.get(i).getName();
                        } else interest = interest + "," + lstInterests.get(i).getName() + ",";
                    }
                }
                Log.e("listInterest", interest);
                user.setDating_status(spn_dating_status.getSelectedItem().toString());
                user.setInterest(interest);
                InsyteApp.getInstance().saveUser(user);
                viewPager.setCurrentItem(2);
                break;
            case R.id.img_dating_status:
                spn_dating_status.performClick();
                break;
        }
    }

    private boolean checkInterestExits(String strCheck) {
        if (lstInterests.size() > 0) {
            for (int i = 0; i < lstInterests.size(); i++) {
                if (strCheck.equalsIgnoreCase(lstInterests.get(i).getName()))
                    return true;
            }
        }
        return false;
    }

    public void getJsonFaceBook() {
        progressDialog.show();
        String url_pull_interests = String.format(url_pull_interests_fb, InsyteApp.getFacebookToken(prefs));
        aQuery.ajax(url_pull_interests, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String response, AjaxStatus status) {
                progressDialog.dismiss();
                if (response != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        FacebookData facebookData = ParserFaceBookUntils.facebookData(jsonObject);
                        List<Category> categories = facebookData.getCategories();
                        Paging paging = facebookData.getPaging();
                        String next = paging.getNext();
                        String befor = paging.getCursors().getBefore();
                        String alter = paging.getCursors().getAfter();
                        if (lstInterests.size() > 0) lstInterests.clear();
                        if (lstFBInterests.size() > 0) lstFBInterests.clear();
                        lstFBInterests.addAll(categories);
                        fb_interest_adapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    initialize.showToast("facebook likes is null");
                }
            }
        });
    }

    /// *************** old code && test reverted
//    private CheckBox chk_pull_facebook;
//    private Spinner spn_dating_status;
//    private ImageView img_dating_status, imgBack;
//    private Button btn_next;
//    private TextView tv_pull_from_facebook;
//    private String arrDattingStatus[] = {
//            "Married", "Single", "Divorced"};
//    //List<CategoryOfInterest> itemList = new ArrayList<CategoryOfInterest>();
//    private ExpandableListView exp_interest;
//    private CallbackManager callbackManager;
//    private ListView exp_my_interest;
//    private ArrayAdapter<String> adapter;
//    private ExpandableInterestAdapter exp_adapter;
//    private MyInterestAdapter my_interest_adapter;
//    private String url_get_interests = Constants.URL_API + "/interests?token=%s";
//    private String url_pull_interests_fb = "https://graph.facebook.com/v2.3/me/likes?access_token=%s";
//    private Initialize initialize;
//    private ProgressDialog progressDialog;
//    private SharedPreferences prefs;
//    private SharedPreferences.Editor editor;
//    private Map<String, Object> params;
//    AQuery aQuery;
//    private List<CategoryOfInterest> lstCategoryOfInterests = new ArrayList<>();
//    private List<CategoryOfInterest> lstCategoriesInterests = new ArrayList<>();
//    private List<InteresetObject> lstInterests = new ArrayList<>();
//    private List<InteresetObject> lstAddToMyInterest = new ArrayList<>();
//    NonSwipeableViewPager viewPager;
//    private User user;
//
//    public interface OnChildItemListener {
//        public void onClick(InteresetObject object);
//    }
//
//    public interface OnMyInterestItemListener {
//        public void onClick(InteresetObject object);
//    }
//
//
//    public ProfileFavourisFragment setViewPager(NonSwipeableViewPager viewPager) {
//        this.viewPager = viewPager;
//        return this;
//    }
//
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        aQuery = new AQuery(getActivity());
//        user = InsyteApp.getInstance().getUser();
//        prefs = getActivity().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
//        editor = prefs.edit();
//        params = new HashMap<String, Object>();
//        initialize = new Initialize(getActivity());
//        progressDialog = initialize.createProgressDialog("Loading");
//        initExpandableData();
//        FacebookSdk.sdkInitialize(getActivity());
//        callbackManager = CallbackManager.Factory.create();
//
//
//    }
//
//    private void initExpandableData() {
//        lstCategoryOfInterests.clear();
//        if (lstCategoriesInterests.size() > 0) lstCategoriesInterests.clear();
//        String url_getInterest = String.format(url_get_interests, InsyteApp.getInstance().getUser().getToken());
//        aQuery.ajax(url_getInterest, JSONObject.class, new AjaxCallback<JSONObject>() {
//            @Override
//            public void callback(String url, JSONObject js, AjaxStatus status) {
//                progressDialog.dismiss();
//                if (result != null) {
//                    try {
//                        if (js.has("code")) {
//                            if (js.getInt("code") == 1) {
//                                lstCategoryOfInterests = ParserUtils.parerInterest(js);
//                                Log.d("interestSize", lstCategoryOfInterests.size() + "");
//                                lstCategoriesInterests.addAll(lstCategoryOfInterests);
//                                exp_adapter.notifyDataSetChanged();
//                            }
//                            //initialize.showToast(js.getString("message"));
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                } else {
//                    initialize.showToast("check server");
//                }
//            }
//        }.header("Content-Type", "application/x-www-form-urlencoded"));
//    }
//
//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        // Inflate the layout for this fragmentS
//        View view = inflater.inflate(R.layout.fragment_profile_favouris, container, false);
//        getViewController(view);
//        if (InsyteApp.getTypeLoginEnum(getActivity()).equals(InsyteEnums.TypeLogin.FB)) {
//            chk_pull_facebook.setEnabled(true);
//            tv_pull_from_facebook.setEnabled(true);
//        } else {
//            chk_pull_facebook.setEnabled(false);
//            tv_pull_from_facebook.setEnabled(false);
//        }
//        if (user.getDating_status() != null) {
//            if (user.getDating_status().equalsIgnoreCase("single")) {
//                spn_dating_status.setSelection(1);
//            } else {
//                spn_dating_status.setSelection(0);
//            }
//        }
//        return view;
//    }
//
//    private void getViewController(View v) {
//        btn_next = (Button) v.findViewById(R.id.btn_next);
//        btn_next.setOnClickListener(this);
//        chk_pull_facebook = (CheckBox) v.findViewById(R.id.chk_pull_facebook);
//        chk_pull_facebook.setBackgroundResource(R.drawable.ic_un_check);
//        chk_pull_facebook.setEnabled(false);
//        spn_dating_status = (Spinner) v.findViewById(R.id.spn_dating_status);
//        tv_pull_from_facebook = (TextView) v.findViewById(R.id.tv_pull_from_facebook);
//        tv_pull_from_facebook.setEnabled(false);
//        imgBack = (ImageView) v.findViewById(R.id.imgBack);
//        img_dating_status = (ImageView) v.findViewById(R.id.img_dating_status);
//        btn_next = (Button) v.findViewById(R.id.btn_next);
//        exp_interest = (ExpandableListView) v.findViewById(R.id.exp_interest);
//        exp_my_interest = (ListView) v.findViewById(R.id.exp_my_interest);
//        exp_adapter = new ExpandableInterestAdapter(getActivity(), lstCategoriesInterests, new OnChildItemListener() {
//            @Override
//            public void onClick(InteresetObject object) {
//                lstCategoriesInterests.remove(object);
//                lstInterests.add(0, object);
//                Log.e("thangpv", object.getName());
//                // lstInterests.addAll(lstAddToMyInterest);
//                my_interest_adapter.notifyDataSetChanged();
//                exp_adapter.notifyDataSetChanged();
//            }
//        });
//        my_interest_adapter = new MyInterestAdapter(getActivity(), lstInterests, new OnMyInterestItemListener() {
//            @Override
//            public void onClick(InteresetObject object) {
//                lstInterests.remove(object);
//                my_interest_adapter.notifyDataSetChanged();
//            }
//        });
//        exp_interest.setAdapter(exp_adapter);
//        exp_my_interest.setAdapter(my_interest_adapter);
//        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, arrDattingStatus);
//        adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
//        spn_dating_status.setAdapter(adapter);
//        imgBack.setOnClickListener(this);
//        chk_pull_facebook.setOnClickListener(this);
//        tv_pull_from_facebook.setOnClickListener(this);
//    }
//
//    @Override
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.chk_pull_facebook:
//                if (!chk_pull_facebook.isChecked()) {
//                    chk_pull_facebook.setBackgroundResource(R.drawable.ic_check);
//                    String url_pull_interests = String.format(url_pull_interests_fb, InsyteApp.getFacebookToken(prefs));
//                    new GraphRequest(AccessToken.getCurrentAccessToken(), url_pull_interests,
//                            null, HttpMethod.GET,
//                            new GraphRequest.Callback() {
//                                public void onCompleted(GraphResponse response) {
//                                    //Log.e("likes", response.toString());
//                                    //{Response:  responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 190, errorType: OAuthException, errorMessage: Malformed access token CAABh3Uf1Ho4BAOvlMZASZCk1PSKSXzmZCZCYVzQ35FMydQoQ0OsalT9yhluC9z5x8Ni6BiWjFLqkYls1dewLt9y3IykzRR9pbsHEfvlaLQyBFl7RVYuoH5LFOUMwXKq4LiZCrwStk7LWZCs57yZCZC3cTvaCJuvIZCx27rZBp0ZBsAVQ8TdZB7MqZB828BJkmFK7ZCXmSGMVNJ5YLpyNZAGcS9yGsKR?format=json}}
////                                    Log.e("responseCode : ", "" + response.getJSONObject().getInt("responseCode"));
////                                    Log.e("request was: ", "" + response.getRequest());
////                                    String resp = response.getRawResponse();
//                                    Log.e("response", response.toString());
//                                    //parseDataFb(response.toString());
//                                    //Log.e("response is: ", "" + resp);
//                                }
//                            }
//                    ).executeAsync();
////                    new GraphRequest(AccessToken.getCurrentAccessToken(),
////                            "/" + AccessToken.getCurrentAccessToken().getUserId() + "/likes",
////                            null,
////                            HttpMethod.GET,
////                            new GraphRequest.Callback() {
////                                public void onCompleted(GraphResponse response) {
////                                    try {
////                                        Log.e("Object Length is : ", "" + response.getJSONObject().length());
////                                        Log.e("request was: ", "" + response.getRequest());
////                                        String resp = response.getRawResponse();
////                                        Log.e("response", response.toString());
////                                        //parseDataFb(response.toString());
////                                        Log.e("response is: ", "" + resp);
////                                    } catch (Exception e) {
////                                        Toast.makeText(getActivity(), "error is: " + e.toString(), Toast.LENGTH_LONG).show();
////                                    }
////                                }
////                            }
////                    ).executeAsync();
//
//                } else {
//                    chk_pull_facebook.setBackgroundResource(R.drawable.ic_un_check);
//                }
//                break;
//            case R.id.tv_pull_from_facebook:
//                chk_pull_facebook.performClick();
//                break;
//            case R.id.imgBack:
//                viewPager.setCurrentItem(0);
//                break;
//            case R.id.btn_next:
//                Log.e("dating", spn_dating_status.getSelectedItem().toString());
//                String interest = "";
//                if (lstInterests.size() > 0) {
//                    for (int i = 0; i < lstInterests.size(); i++) {
//                        if (i == lstInterests.size() - 1)
//                            interest = interest + "," + lstInterests.get(i).getName();
//                        else if (i == 0) {
//                            interest = lstInterests.get(i).getName();
//                        } else interest = interest + "," + lstInterests.get(i).getName() + ",";
//                    }
//                }
//                Log.e("listInterest", interest);
//                user.setDating_status(spn_dating_status.getSelectedItem().toString());
//                user.setInterest(interest);
//                InsyteApp.getInstance().saveUser(user);
//                viewPager.setCurrentItem(2);
//                break;
//            case R.id.img_dating_status:
//                spn_dating_status.performClick();
//                break;
//        }
//    }
//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        callbackManager.onActivityResult(requestCode, resultCode, data);
//    }
}
